﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Common
{
    /// <summary>
    /// 提供文件读取的方法
    /// </summary>
    /// <remarks>
    /// 如果直接使用System.IO.File.ReadAllText方法读取文件，有可能产生“文件正由另一进程使用，因此该进程无法访问此文件”的异常，因此以FileStream的方式读取
    /// </remarks>
    public class FileReader
    {

        public static string ReadAllText(string fileFullPath, Encoding encoding)
        {
            byte[] fileBytes = ReadAllBytes(fileFullPath);
            if (fileBytes == null)
                return null;
            else
                return encoding.GetString(fileBytes);
        }

        public static byte[] ReadAllBytes(string fileFullPath)
        {
            using (FileStream fileStream = new FileStream(fileFullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                if (!fileStream.CanRead)
                {
                    throw new Exception("文件流不可读");
                }
                else if (fileStream.Length <= 0)
                {
                    return null;
                }
                else
                {
                    byte[] fileBuffer = null;
                    int nRead = 0;
                    fileBuffer = new byte[fileStream.Length];
                    nRead = fileStream.Read(fileBuffer, 0, (int)fileStream.Length);
                    if (nRead == fileStream.Length)
                    {
                        return fileBuffer;
                    }
                    else
                    {
                        throw new Exception("未能完整读取文件流");
                    }
                }
            }

        }
    }
}
